<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use think\Config;
use think\Validate;
use think\Lang;
use app\common\model\Third;
use app\admin\model\sport\Setting as SettingModel;
use app\admin\model\sport\Area as AreaModel;
use app\admin\model\sport\Score as ScoreModel;
use app\admin\model\sport\Teacher as TeacherModel;
use app\admin\model\sport\ScoreType as ScoreTypeModel;
use app\common\library\Score as ScoreLib;
use Grafika\Grafika;
use Grafika\Color;

/**
 * 小程序接口
 */
class Mp extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $scoreTypes = [
        'middle'  => '中考体育评分',
        'senior'  => '高考体育评分',
    ];
    protected $units = [
        'ms'  => '分.秒',
        'meter'  => '米',
        'cmeter'  => '厘米',
        'sec' => '秒',
        'an' => '个',
    ];

    public function _initialize()
    {
        parent::_initialize();
        $allSettings = SettingModel::getSettings(); 
    }

    public function getArea()
    {
        $data = AreaModel::where('status', 'normal')->select(); 
        $res = [];
        foreach ($data as $ap) {
            $res[] = [
                'id' => $ap->id,
                'name'  => $ap->area_name,
            ];
        }

        $this->success('获取成功', $res); 
    }

    public function getScoreList()
    {
        $areaId = $this->request->get('area_id', 0);
        if (empty($areaId)) {
            $areaId = 1;
        }
        $res = [];
        $area = AreaModel::where('status', 'normal')->where('id', $areaId)->find(); 
        if (!$area) {
            $this->success('获取成功', $res); 
        }
        $scoreModel = new ScoreModel;
        $data = $scoreModel->where('sport_area_id', $areaId)
                           ->where('status', 'normal')
                           ->distinct(true)->field('score_type')
                           ->select();
        foreach ($data as $ap) {
            $virtualPersons = $ap->score_type == 'middle' ? $area->middle_vitural : $area->senior_virtual;
            // $virtualPersons = mt_rand(1000, 2000);
            $res[] = [
                'score_type' => $ap->score_type,
                'area_id' => $areaId,
                'name'  => $area->area_name . $this->scoreTypes[$ap->score_type],
                'persons' => $virtualPersons,
            ];
        }

        $this->success('获取成功', $res); 
    }

    public function getScoreItems()
    {
        $areaId = $this->request->get('area_id', 0);
        if (empty($areaId)) {
            $this->error('缺少地区参数!');
        }
        $scoreType = $this->request->get('score_type', '');
        if (empty($scoreType)) {
            $this->error('缺少类别参数');
        }
        $sex = $this->request->get('sex', '1');
        $data = ScoreModel::where('sport_area_id', $areaId)->where('status', 'normal')
                                                           ->where('score_type', $scoreType)->where('sex', $sex)
                                                           ->order('weigh', 'desc')
                                                           ->select();
        $scores = [];
        foreach ($data as $ap) {
            $scores[] = [
                'score_id' => $ap->id,
                'project_name' => $ap->project_name,
                'unit'  => $ap->unit,
                'unit_name' => $this->units[$ap->unit],
                'show_unit' => !empty($ap->show_unit) ? $ap->show_unit : $this->units[$ap->unit],
                'show_val' => !empty($ap->show_val) ? $ap->show_val : '0',
                'type_id' => $ap->sport_type_id,
            ];
        }
        // 进行虚拟的数字加一
        $area = AreaModel::where('id', $areaId)->find(); 
        // 先查找项目类别
        $scoreRes = [];
        if ($scoreType == 'middle') {
            $types = [];
            $typeNames = [];
            $scoreTypes = ScoreTypeModel::where('sport_area_id', $areaId)->where('status', 'normal')->select();
            foreach ($scoreTypes as $st) {
                $types[$st->id]  = [];  
                $typeNames[$st->id] = $st->type_name;
            }

            foreach ($scores as $s) {
                if (isset($types[$s['type_id']]))  {
                    $types[$s['type_id']][] = $s;
                } 
            }
            foreach ($types as $typeId => $t) {
                if (!empty($t)) {
                    $scoreRes[] = [
                      'name' => $typeNames[$typeId],
                      'list' => $t,
                    ];
                }
            }
            $area->middle_vitural = $area->middle_vitural + mt_rand(1, 3);
        } else {
            foreach ($scores as $s) {
                $scoreRes[] = [
                  'name' => '',
                  'list' => [$s],
                ];
            }
            $area->senior_virtual = $area->senior_virtual + mt_rand(1, 3);
        }
        $area->save();
        $res = [
            'area_id' => $areaId,
            'score_type' => $scoreType,
            'sex' => $sex,
            'score_res' => [],
        ];
        $res['score_res'] = $scoreRes;

        $this->success('获取成功', $res); 
    }

    public function calScoreItem()
    {
        $res = [
            'point' => '0'
        ];
        $scoreId = $this->request->post('score_id', 0);   
        if (empty($scoreId)) {
            $this->error('缺少计算项目参数!');
        }
        $score = $this->request->post('score', '0');
        if (empty($score)) {
            $this->success('获取成功', $res); 
        }
        // 开始计算
        $scoreData = ScoreModel::where('status', 'normal')->find($scoreId);
        if (!$scoreData) {
            $this->error('计算项目不存在!');
        }
        $scoreSetting = $scoreData->score_setting;
        if (empty($scoreSetting)) {
            $this->error('未设置区间!');
        }
        $tmpScore = trim($score, ".");
        if ($tmpScore === $score) {
            $scoreLib = new ScoreLib();
            // 进行转换
            $scoreRes = $scoreLib->convertScore($score, $scoreData->unit, empty($scoreData->show_unit) ? $scoreData->unit : $scoreData->show_unit);
            $res['point'] = $scoreLib->calPoint($scoreSetting, $scoreRes[0]);
        }
        /*
        if (empty($res['point'])) {
            $this->error('成绩不在设置区间范围内, 请联系管理员!');
        }
         */

        $this->success('获取成功', $res); 
    }

    public function calScoreTotal()
    {
        $res = [
            'score_total' => 0,
            'level_code' => '',
            'level_name' => '',
        ];
        $scoreLib = new ScoreLib();
        $areaId = $this->request->post('area_id', 0);
        $scoreType = $this->request->post('score_type', '');
        $sex = $this->request->post('sex', 0);
        if (empty($areaId) || empty($scoreType) || empty($sex)) {
            $this->error('缺少必要参数!');
        }
        $scores = $this->request->post('scores/a');
        if (empty($scores)) {
            $this->error('未传递计算的体育项!');
        }
        $newScores = [];
        foreach ($scores as $s) {
            // 只需要判断有输入成绩
            if (!empty($s['score'])) {
                $newScores[] = $s;
            }
        }
        $calRes = $scoreLib->calScore($newScores, $areaId, $scoreType, $sex);
        if (!empty($calRes['msg'])) {
            $this->error($calRes['msg']);
        }
        $res = $calRes['res'];
        // 增加自动反馈
        $feedbacks = $scoreLib->createAutoFeedback(0, $newScores);
        $teacher = TeacherModel::get($feedbacks[1]);
        $res['feedback_status'] = "2";
        $res['feedback_content'] = $feedbacks[0];
        $teacher['icon_image'] =  cdnurl($teacher['icon_image'], true);
        $res['teacher'] = $teacher;

        $this->success('获取成功', $res); 
    }

}
